package com.esayread

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.esayread.navigation.BottomNavItem
import com.esayread.ui.account.AccountScreen
import com.esayread.ui.bookshelf.BookshelfScreen
import com.esayread.ui.bookshelf.BookSelectionScreen
import com.esayread.ui.history.ReadingHistoryScreen
import com.esayread.ui.reading.ReadingScreen
import com.esayread.ui.theme.EsayReadTheme
import com.esayread.data.Book
import com.esayread.data.BookFormat
import androidx.navigation.NavType
import androidx.navigation.navArgument
import com.google.gson.Gson
import java.net.URLEncoder
import java.nio.charset.StandardCharsets

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            EsayReadTheme {
                EsayReadApp()
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EsayReadApp() {
    val navController = rememberNavController()
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentDestination = navBackStackEntry?.destination

    // 检查当前是否在阅读界面
    val isReadingScreen = currentDestination?.route?.startsWith("reading/") == true
    
    Scaffold(
        modifier = Modifier.fillMaxSize(),
        bottomBar = {
            // 只在非阅读界面显示底部导航栏
            if (!isReadingScreen) {
                NavigationBar {
                    BottomNavItem.values().forEach { item ->
                        NavigationBarItem(
                            icon = {
                                Icon(
                                    imageVector = item.icon,
                                    contentDescription = item.title
                                )
                            },
                            label = { Text(item.title) },
                            selected = currentDestination?.hierarchy?.any { it.route == item.route } == true,
                            onClick = {
                                navController.navigate(item.route) {
                                    // Pop up to the start destination of the graph to
                                    // avoid building up a large stack of destinations
                                    // on the back stack as users select items
                                    popUpTo(navController.graph.findStartDestination().id) {
                                        saveState = true
                                    }
                                    // Avoid multiple copies of the same destination when
                                    // reselecting the same item
                                    launchSingleTop = true
                                    // Restore state when reselecting a previously selected item
                                    restoreState = true
                                }
                            }
                        )
                    }
                }
            }
        }
    ) { innerPadding ->
        NavHost(
            navController = navController,
            startDestination = BottomNavItem.BOOKSHELF.route,
            modifier = Modifier.padding(innerPadding)
        ) {
            composable(BottomNavItem.BOOKSHELF.route) {
                BookshelfScreen(
                    navController = navController,
                    onBookClick = { book ->
                        // 导航到阅读页面
                        val bookJson = Gson().toJson(book)
                        val encodedBookJson = URLEncoder.encode(bookJson, StandardCharsets.UTF_8.toString())
                        navController.navigate("reading/$encodedBookJson")
                    }
                )
            }
            composable("book_selection") {
                BookSelectionScreen(
                    navController = navController,
                    onBooksSelected = { selectedBooks ->
                        // 书籍已经复制到应用目录，BookSelectionScreen会自己处理导航
                        // 这里不需要额外的导航操作
                    }
                )
            }
            composable(BottomNavItem.READING.route) {
                ReadingHistoryScreen(
                    onHistoryClick = { history ->
                        // TODO: 根据阅读历史导航到阅读页面
                        // 这里需要根据bookId获取Book对象
                    }
                )
            }
            composable(
                "reading/{bookJson}",
                arguments = listOf(navArgument("bookJson") { type = NavType.StringType })
            ) { backStackEntry ->
                val encodedBookJson = backStackEntry.arguments?.getString("bookJson") ?: ""
                val bookJson = java.net.URLDecoder.decode(encodedBookJson, StandardCharsets.UTF_8.toString())
                ReadingScreen(
                    navController = navController,
                    bookJson = bookJson
                )
            }
            composable(BottomNavItem.ACCOUNT.route) {
                AccountScreen()
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun EsayReadAppPreview() {
    EsayReadTheme {
        EsayReadApp()
    }
}